/**
 * @author SilverBiology, LLC
 * @website http://code.google.com/p/gbif-spreadsheet-processor/
*/
Ext.namespace('GBIF');
Ext.namespace('GBIF.GeoSpatial')

GBIF.GeoSpatial.LayersTree = function(config){

	this.opacitySlider = new GeoExt.LayerOpacitySlider({
			width: 100
		,	x: 10
		,	y: 10
		, increment: 10
		,	plugins: new GeoExt.LayerOpacitySliderTip()
		,	value: 100
		,	aggressive: false
		,	changeVisibility: true
		,	hidden: true
	});

	this.btnRemoveNode = new Ext.Button({
			width: 20
		,	iconCls: 'gbif-bin'
		, 	handler: this.removeNode
		,	tooltipType : 'qtip'
		,	tooltip : this.txtRemoveTooTip
		,	hidden: true
		,	scope: this
	});

	this.addButton = new Ext.Button({
			width:20
		,	text:this.txtAddLayer
		,	scope:this
		, handler: this.addLayer
		,	hidden: true
	});

	this.opacityT = new Ext.Toolbar.TextItem({
			text: this.txtOpacity
		,	hidden: true
	});

	Ext.apply(this, config, {
			rootVisible: Config.GBIF.GeoSpatial.LayersTree.rootVisible
		,	enableDD: Config.GBIF.GeoSpatial.LayersTree.enableDD
		,	useArrows: Config.GBIF.GeoSpatial.LayersTree.useArrows	
		,	minWidth: Config.GBIF.GeoSpatial.LayersTree.width-20
		,	maxWidth: Config.GBIF.GeoSpatial.LayersTree.width+20
		,	cls: Config.GBIF.GeoSpatial.LayersTree.cls
		/*
		 * Doesn't have data like mType & description Need to check what to show as data tip.
		,	plugins: new Ext.ux.DataTip({
					tpl:new Ext.XTemplate(
								'<div>'+
						 				'<tpl if="mType != 0">'+
											'Type: {mType} '+
										'</tpl>'+
										'<tpl if="description != 0">'+
											'<br> Description: {description}</div>'+
										'</tpl>'+	
								 '</div>'							
							)
				})
		*		
		*/
		,	root: new GeoExt.tree.LayerContainer({
					text: 'Map Layers'
				,	layerStore: config.layers
				,	leaf: false
				,	expanded: true
			})
		,	bbar: {
					height: 25
				,	items: [
							this.opacityT
						,	this.opacitySlider
						, '->'
						,	this.btnRemoveNode
					]
			}
		,	listeners: {
					click: function(node){
						this.showComp();
						if (node.layer.isBaseLayer) {
							this.hideComp(false, false);
						} else {
							this.hideComp( node.layer.options.allowOpacity, node.layer.options.allowDelete );
						}
						
						this.opacitySlider.layer = node.layer;
						
						if((typeof node.layer.params == 'undefined') ? false : true){
							if (Ext.isEmpty(node.layer.opacity)){
								this.opacitySlider.setValue(100);
							} else {
								this.opacitySlider.setValue(node.layer.opacity * 100);
							}	
						}
					}
				,	contextmenu: this.charactercontextmenu
				,	beforerender: this.addCustomEvents				
				,	afterrender: this.changeToCheckbox	
			}
	});
	
	GBIF.GeoSpatial.LayersTree.superclass.constructor.call(this, config);
}

Ext.extend(GBIF.GeoSpatial.LayersTree, Ext.tree.TreePanel, {

		removeNode: function ( btn, e ){
			var tmpNode = this.getSelectionModel().getSelectedNode();
			if (!Ext.isEmpty(tmpNode)) {
					tmpNode.layer.destroy();
					this.changeToCheckbox();
					this.fireEvent('nodeDeleted',tmpNode,this);
			}
			this.hideComp( false, false );
		}

	,	addCustomEvents:function(){
			this.addEvents('afterDroped');
			this.addListener( 'afterDroped',this.changeToCheckbox,this);
		}
	
	,	changeToCheckbox : function(){
			var root = this.getRootNode();
			Ext.each(root.childNodes,function(node){
				if (node.text == "World Map") {
					node.getUI().checkbox.type = 'checkbox';
					node.getUI().checkbox.checked = true;
					Ext.fly(node.getUI().checkbox).hide();
				}
			}, this);
		}
	
	,	charactercontextmenu: function(node){
			node.select();
			this.fireEvent("click", node);
			
			if (node.layer.options.allowDelete == false) {
				return;
			}
			
			var menu = new Ext.menu.Menu();
			var exportmenu = [];
			
			if(typeof node.attributes.layer.downloadFormats != 'undefined'){
				
				if(node.attributes.layer.downloadFormats.Image){
					exportmenu.push(Config.General.ContextMenu.exportMenu.Image);
				}
						
				if(node.attributes.layer.downloadFormats.CSV){
					exportmenu.push(Config.General.ContextMenu.exportMenu.CSV);
				}
					
				if(node.attributes.layer.downloadFormats.GML2){
					exportmenu.push(Config.General.ContextMenu.exportMenu.GML2);
				}
					
				if(node.attributes.layer.downloadFormats.GML2GZIP){
					exportmenu.push(Config.General.ContextMenu.exportMenu.GML2GZIP);
				}
					
				if(node.attributes.layer.downloadFormats.GeoJSON){
					exportmenu.push(Config.General.ContextMenu.exportMenu.GeoJSON);
				}
					
				if(node.attributes.layer.downloadFormats.Shapefile){
					exportmenu.push(Config.General.ContextMenu.exportMenu.Shapefile);
				}				
			}
			
			if (!node.layer.isBaseLayer) {
				menu.add({
						text: this.txtRemoveLayer
					,	handler: this.removeNode.createDelegate(this, [node])
				});
			}
			
			if(!Ext.isEmpty(exportmenu)){
				menu.add({
					text: this.txtExport
				,	scope: this	
				,	menu: {
							items: exportmenu
						,	scope: this
						}
					})
			}

			if (menu.items && menu.items.length > 0) {
				menu.show(node.ui.getAnchor());
			}
		}

	,	exportImage:function(format){
				var exportformat='';
				switch(format) {
					case 'Composite Image':
							exportformat = 'image/png'
						break;
					case 'CSV':
							exportformat = 'csv'
						break;
					case 'GML2':
							exportformat = 'GML2'
						break;
					case 'GML2-GZIP':
							exportformat = 'GML2-GZIP'
						break;
					case 'GeoJSON':
							exportformat = 'json'
						break;	
					case 'Shapefile':
							exportformat = 'SHAPE-ZIP'
						break;				
				}
				var exportdata=[];
				var layer='';
				var tmpNode = this.getSelectionModel().getSelectedNode();
				var maplayer= tmpNode.layer;
				var size = GBIF.GeoSpatial.BUS.fireEvent('calculateHW', this);
				
				if(tmpNode.layer.CLASS_NAME == "OpenLayers.Layer.WMS"){
					layer = {
							version: maplayer.params.VERSION
						,	request: maplayer.params.REQUEST
						,	layers: maplayer.params.LAYERS
						,	styles: maplayer.params.STYLES
						,	bbox: maplayer.map.getExtent().toBBOX()
						,	width: size.width //maplayer.tileSize.w
						,	height: size.height //maplayer.tileSize.h
						,	srs: maplayer.params.SRS || maplayer.params.CRS
						,	opacity: maplayer.opacity || 1
						,	format: exportformat // maplayer.params.FORMAT
						,	url: maplayer.params.URL || maplayer.url
						,	FILTER: maplayer.params.FILTER
						,	CQL_FILTER: maplayer.params.CQL_FILTER
					}
					exportdata.push(layer);	
					
					if (exportformat != 'image/png') {
						GBIF.GeoSpatial.BUS.fireEvent('exportImage', layer, exportformat, this);
					} else {
						GBIF.GeoSpatial.BUS.fireEvent('exportImage', exportdata, exportformat, this);
					}
				}else{
					GBIF.GeoSpatial.Notice.msg('Notice','Only wms layers are allowed.');
				}
			}
	
	,	showComp: function (){
			this.opacitySlider.show();
			this.opacityT.show();
			this.btnRemoveNode.show();
		}

	,	hideComp: function( opacity, remove ){
			opacity = (typeof opacity == 'undefined') ? true : opacity;
			remove = (typeof remove == 'undefined') ? true : remove;

			if (!opacity) {
				this.opacitySlider.hide();
				this.opacityT.hide();
			}
			
			if (!remove) {
				this.btnRemoveNode.hide();
			}
		}

});